import { View } from "@tarojs/components";
import Taro, { useLoad, useRouter, useDidShow } from "@tarojs/taro";
import { ItemView } from "../../components";
import { useRef, useState } from "react";
import { fetchCartList, fetchCart } from "../../utils/api";

const CartPage = () => {
  const [cartList, setCartList] = useState<any[]>([]);
  let routerPath = useRef("");
  // 注意： hook 必须是定义在函数顶层
  const router = useRouter();
  const pageOpt = useRef({ page: 1, size: 5 });

  // 获取路由信息
  useDidShow(() => {
    // 注意： 生命周期中，不能使用hook
    routerPath.current = router.path;
    console.log("购物车页面中", router.path);
  });

  // 1. 请求购物车数据
  const fetchCartData = async () => {
    const cartRes = await fetchCartList({ ...pageOpt.current });
    // const cartRes = await fetch("http://localhost:9999/cart", "GET", {});
    // console.log("cartRes:", cartRes.data);
    setCartList(cartRes);
  };

  useLoad(() => {
    fetchCartData();
  });

  const handleCartClick = async (item: any, tip: string) => {
    console.log("item:", item);
    if (tip === "add") {
      item.number++;
    } else {
      item.number--;
    }
    console.log("add:", item);
    try {
      // 调用更新接口
      // const addRes = await fetch(
      //   `http://localhost:9999/cart/${item.id}`,
      //   "PATCH",
      //   item
      // );
      const addRes = await fetchCart({ item });
      // 重新调用渲染接口
      fetchCartData();
      Taro.showToast({ title: "加入成功" });
    } catch (error) {
      Taro.showToast({ title: "加入失败" });
    }
  };

  // // 2. ++
  // const handleAddCart = async (item: any) => {};

  // // 3. --
  // const handleReduceCart = async (item: any) => {};

  return (
    <View>
      {/* 购物车页面  routerPath === ‘/pages/cart/cart’*/}
      {cartList.map((item) => {
        return (
          <ItemView
            item={item}
            addCartClick={() => handleCartClick(item, "add")}
            reduceCartClick={() => handleCartClick(item, "reduce")}
            routerPath={routerPath.current}
          ></ItemView>
        );
      })}
    </View>
  );
};

export default CartPage;
